import Vue from 'vue'

export function debounce(fn, delay) {
  var delay = delay || 200;
  var timer;
  return function () {
      var th = this;
      var args = arguments;
      if (timer) {
          clearTimeout(timer);
      }
      timer = setTimeout(function () {
          timer = null;
          fn.apply(th, args);
      }, delay);
  };
}

export function throttle(fn, interval) {
  var last;
  var timer;
  var interval = interval || 200;
  return function () {
      var th = this;
      var args = arguments;
      var now = +new Date();
      if (last && now - last < interval) {
          clearTimeout(timer);
          timer = setTimeout(function () {
              last = now;
              fn.apply(th, args);
          }, interval);
      } else {
          last = now;
          fn.apply(th, args);
      }
  }
}

export function confirmLater (promise) {
  return new Promise((resolve, reject) => {
    promise.on('transactionHash', resolve);
    promise.on('error', reject);
    function onConfirm (confNumber, receipt) {
      promise.off('confirmation', onConfirm);
    }
    promise.on('confirmation', onConfirm);
  });
}

export function getHashParams (hash) {
  if(!hash) return [];
  return (hash || '').replace(/#\/|#/gi, '').replace(/\/$/, '').split('/');
}

export function formatNumber(number, dec = 2, dsep, tsep) {
  if(number == 0) return 0
  if (isNaN(+number) || number == null) return '';
  number = parseFloat(number)
  number = number.toFixed(~~dec);
  tsep = typeof tsep == 'string' ? tsep : ',';

  var parts = number.split('.'),
    fnums = parts[0],
    decimals = parts[1] ? (dsep || '.') + parts[1] : '';

  return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
}

export function isDivisibleBy(dividend) {
  return divisor => {
    const quotient = dividend / divisor;
    const diff = Math.abs(Math.round(quotient) - quotient);
    return diff < Number.EPSILON * 0b100;
  };
}

Vue.filter('formatNumber', formatNumber)
